package store.lunangangster.engine.impl.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import store.lunangangster.engine.impl.Context;

public class DeploymentEntityImpl extends EntityImpl implements DeploymentEntity {

  // DB property
  protected String name;
  protected String key;
  protected Date deployTime;

  // no persist
  protected boolean isNew;

  // cache
  protected List<ResourceEntity> resources;


  @Override
  public String getId() {
    return id;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public String getKey() {
    return key;
  }

  @Override
  public Date getDeployTime() {
    return deployTime;
  }

  @Override
  public boolean isNew() {
    return isNew;
  }

  @Override
  public void setId(String id) {
    this.id = id;
  }

  @Override
  public void setName(String name) {
    this.name = name;
  }

  @Override
  public void setKey(String key) {
    this.key = key;
  }

  @Override
  public void setDeployTime(Date deployTime) {
    this.deployTime = deployTime;
  }

  @Override
  public void addResource(ResourceEntity resource) {
    if (resources == null) {
      resources = new ArrayList<>();
    }
    resources.add(resource);
  }

  // Lazy loading
  @Override
  public List<ResourceEntity> getResources() {
    if (resources == null) {
      List<ResourceEntity> resourceEntities = Context.getProcessEngineConfiguration()
          .getResourceEntityManager().selectResourcesByDeploymentId(id);
      List<ResourceEntity> resourceList = new ArrayList<>(resourceEntities.size());

      resourceList.addAll(resourceEntities);

      resources = resourceList;
    }

    return resources;
  }

  @Override
  public void setNew(boolean isNew) {
    this.isNew = isNew;
  }

  @Override
  public Object getPersistState() {
    Map<String, Object> persistState = new HashMap<>();

    persistState.put("name", name);
    persistState.put("key", key);
    persistState.put("deployTime", deployTime);
    return persistState;
  }
}
